package cn.zhc.com.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by zhouhongchun on 2017/8/14.
 */

public class UtilsNet {

    /**
     * 和ping结合使用
     * @param context
     * @return
     */
    public static boolean checkNet(Context context) {
        return checkWifi(context) || checkMobile(context);
    }

    public static boolean checkWifi(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (mNetworkInfo == null) return false;
        return mNetworkInfo.isConnected() && mNetworkInfo.isAvailable();
    }

    public static boolean checkMobile(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        return mNetworkInfo.isAvailable();
    }

    /**
     * 和checkNet结合使用
     * @param networkState
     * @return
     */
    public static boolean ping(boolean networkState) {

        InputStream input = null;
        BufferedReader in;
        StringBuffer stringBuffer;
        if (networkState) {
            try {
                String ip = "www.baidu.com";//之所以写百度是因为百度比较稳定，一般不会出现问题，也可以ping自己的服务器
                Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping3次
                // 读取ping的内容
                input = p.getInputStream();
                in = new BufferedReader(new InputStreamReader(input));
                stringBuffer = new StringBuffer();
                String content = "";
                while ((content = in.readLine()) != null) {
                    stringBuffer.append(content);
                }
                // PING的状态
                int status = p.waitFor();  //status 为 0 ，ping成功，即为可以对外访问；为2则失败，即联网但不可以上网
                if (status == 0) {
                    //"net is  available"
                    return true;
                } else {
                    //net is not available
                    return false;
                }
            } catch (IOException e) {
                //"IOException"
            } catch (InterruptedException e) {
                //"InterruptedException"
            } finally {

                if (input != null) {

                    try {
                        input.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
        return false;
    }
}
